package com.ailink.concurrent.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by Administrator on 2018/10/17
 */
@Slf4j
public class ReentrantReadWriteLockTest {

    public void read() {
        readLock.lock();
        System.out.println("read");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        readLock.unlock();
    }

    public void write() {
        writeLock.lock();
        System.out.println("write");
        try {
            Thread.sleep( 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        writeLock.unlock();
    }

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    public static void main(String[] args) throws InterruptedException {
//        ReentrantReadWriteLockTest test = new ReentrantReadWriteLockTest();
//        new Thread(() -> test.write()).start();
//        try {
//            Thread.sleep(100);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        for (int i = 0; i < 1; i++) {
//            new Thread(() -> test.read()).start();
//        }

        ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
        rwl.writeLock().lock();
        rwl.readLock().lock();
        rwl.writeLock().unlock();

        new Thread(() -> {
            log.info("rwl.readLock().lock() 0");
            rwl.readLock().lock();
            log.info("rwl.readLock().lock() 1");
            log.info("rwl.readLock().unlock() 0");
            rwl.readLock().unlock();
            log.info("rwl.readLock().unlock() 1");

            log.info("rwl.writeLock().lock() 0");
            rwl.writeLock().lock();
            log.info("rwl.writeLock().lock() 1");
            log.info("rwl.writeLock().unlock() 0");
            rwl.writeLock().unlock();
            log.info("rwl.writeLock().unlock() 1");
        }).start();

        log.info("sleep 0");
        Thread.sleep(1000);
        log.info("sleep 1");
        rwl.readLock().unlock();
    }

}
